var spider = require('../dao/spider');
var utils = require('../dao/utils');
var insertDB = require('./insert.db');
var fs = require('fs');
var cheerio = require('cheerio');
var request = require('request');
var page = {
    curPage: 5,
    totalPage: 267,
};


var url = "http://www.manhuagui.com/list/index_p*PageReplace*.html";

spider.pageNext(url, page, callback);

// module.exports = function (successCall) {

//     spider.successCall = successCall;
//     spider.pageNext(url, page, callback);
// };


function callback(err, body, _url) {
    if (err) {
        console.log(err);
        return;
    }

    var res;
    try {
        res = body.toString('utf-8');
    } catch (e) {
        console.log(e);
    }

    var $ = cheerio.load(res);

    // list/index_p597.html
    if ($('#AspNetPager1 a').eq(-1).attr('href')) {
        page.totalPage = $('#AspNetPager1 a').eq(-1).attr('href');

        page.totalPage = page.totalPage.match(/\d+/)[0];

        console.log(page.totalPage);
    }

    dataInit($, _url);
    // if(page.totalPage == page.curPage){
    //     spider.successCall(null,'success');
    //     spider.successCall = function(){};
    // }
}


// page页数据处理
function dataInit($, url) {

    var liArry = $('#contList li');

    if (liArry.length == 0) {
        console.log('no lis');
        return false;
    }

    for (var i = 0; i < liArry.length; i++) {
        var item = liArry.eq(i);
        var name = item.find('.ell').find("a").text();
        var url = utils.host(url)+item.find('.ell').find("a").attr('href');

        console.log(url);
        //detail  
        getDetail(url, name);

    }

}


function getDetail(d_url, name) {


    request({ url: d_url, encoding: null,timeout:10000 }, function (err, res, body) {
        var res;
        try {
            res = body.toString('utf-8');
        } catch (e) {

            getDetail(d_url, name);
        }

        if(!res){
            console.log('error-'+name+':'+d_url);
            console.log(res);
            getDetail(d_url, name);

            return;
        }
        // console.log(res);

        var $ = cheerio.load(res);

        detailHtml($,d_url,name);        

        
    });
}

function detailHtml($, url,name) {


    var chaptersLis = $(".chapter-list li");
    var chapter =[];
    for (var i = 0; i < chaptersLis.length; i++) {
        var _cur = chaptersLis.eq(i);

        chapter.push({
            href: utils.host(url)+_cur.find("a").eq(0).attr('href'),
            chapter: _cur.find("a").eq(0).attr('title')+"("+utils.trim(_cur.find("i").eq(0).text())+")"
        });
    }



    var _title = $(".book-title").text();
    _title = utils.trim(_title);

    // info
    var info = $("#intro-all").text();



    var time = $(".status .red").eq(1).text();
    time = utils.trim(time);
    time = utils.timeFormat(time);

    var data = {
        title: _title||name,
        href: url,
        img: $('.book-cover img').attr('src'),
        auth: $(".detail-list li").eq(1).find("a").eq(-1) ? utils.trim($(".detail-list li").eq(1).find("a").eq(-1).text()) : null,

        auth_href: utils.host(url)+$(".detail-list li").eq(1).find("a").eq(-1).attr('href'),

        news: chapter.length > 0 ? chapter[0]['chapter'] : null,
        news_href: chapter.length > 0 ? chapter[0]['href'] : null,

        isFinish: utils.trim($(".status .red").eq(0).text()) == '连载中' ? false : true,

        updateTime: time,

        type:utils.trim($(".detail-list li").eq(1).find("span").eq(0).text().replace("漫画剧情：",'')),

        letter: utils.letter(_title),

        info: utils.trim(info),
        domain: utils.host(url),
        isUpdate: true,
        "chapters": chapter
    };


    insertDB(data);


    // console.log(data);

}


